import APIS from '@/apis';
import ImageUpload from '@/components/ImageUpload';
import RichTextEditor from '@/components/RichTextEditor';
import SearchAbleSelect from '@/components/SearchAbleSelect';
import {Input, Button, Form, Switch, Space, Modal} from 'antd';
import {FormInstance} from 'antd/lib/form';
import React from 'react';
import {Component} from 'react';
import {connect} from 'umi';

class CreateArticle extends Component<any, any> {
  formInstance?: FormInstance | null;

  constructor(props: any) {
    super(props);
    this.state = {
      showAddButton: true,
      editorData: null,
      typeValue: 1,
      tagValue: [],
      imageUrl: '',
      articleContent: '',
    };
  }

  componentWillUnmount() {
    window.onbeforeunload = null;
  }

  componentDidMount() {
    window.onbeforeunload = function (event: any) {
      event.returnValue = "系统不会保存用户数据!";
    };
    var id = null;
    var params = new URLSearchParams(this.props.history.location.search);
    if (params.has('id')) {
      id = parseInt(params.get('id') + '');
      APIS.ArticleAPI.GetArticleDetailes(id).then((data) => {
        if (!data) {
          Modal.error({
            title: "文章没有找到!", onOk: () => {
              this.props.history.goBack()
            }
          })
          return;
        }
        this.setState({
          editorData: data, typeValue: data.typeInfo?.id, imageUrl: data.image, tagValue: data.tags.map((item: any) => {
            return item.id;
          })
        })
        this.rich?.reload();
        this.formInstance?.setFieldsValue({
          title: data?.title,
          author: data?.author,
          tagIds: data?.tag,
          state: data?.state,
          image: data?.image,
          type: data.typeInfo?.id
        })
      });

    }
  }

  rich: RichTextEditor | undefined;

  render() {
    // const {editorData} = this.state;
    const normFile = (e: any) => {
      // console.log('Upload event:', e);
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    };
    return (
      <Form
        ref={(ref) => {
          this.formInstance = ref;
        }}
        style={{marginTop: '20px'}}
        onFinish={(values) => {
          if (this.state.typeValue === -1) {
            alert('请选择文章类型');
            return;
          }
          if (this.state.imageUrl === '') {
            alert('请上传封面图');
            return;
          }
          if (this.state.tagValue.length < 1 || this.state.tagValue.length > 3) {
            alert('请选择1~3个标签');
            return;
          }
          if (this.state.editorData) {
            APIS.ArticleAPI.UpdateArticle({
              id: this.state.editorData.id,
              title: values.title,
              author: values.author,
              type: this.state.typeValue,
              tagIds: this.state.tagValue,
              state: values.state ? 1 : 0,
              image: this.state.imageUrl,
              content: this.state.articleContent,
            }).then((res) => {
              if (res.code === 80109) {
                alert(res.msg);
                return;
              }
              this.props.history.goBack();
            });
          } else {
            APIS.ArticleAPI.CreateNewArticle({
              title: values.title,
              author: values.author,
              type: this.state.typeValue,
              tagIds: this.state.tagValue,
              state: values.state ? 1 : 0,
              image: this.state.imageUrl,
              content: this.state.articleContent,
            }).then((res) => {
              if (res.code === 80109) {
                alert(res.msg);
                return;
              }
              this.props.history.goBack();
            });
          }
        }}
      >
        <Form.Item
          label="文章标题"
          name="title"
          rules={[{required: true, message: '请输入文章标题'}]}
        >
          <Input placeholder="请输入文章标题" disabled={this.state.editorData}/>
        </Form.Item>
        <Form.Item
          name="author"
          hasFeedback
          label="文章作者"
          rules={[{required: true, message: '请输入文章作者'}]}
        >
          <Input placeholder="请输入文章作者"/>
        </Form.Item>

        <Form.Item
          name="type"
          label="文章类型"
          hasFeedback
          validateStatus={this.state.typeValue === -1 ? 'error' : 'success'}
        >
          <SearchAbleSelect
            searchData={async (key) => {
              var datas: Array<any> = await APIS.ArticleAPI.SearchGetTypeList(key);
              return Promise.resolve(
                datas.map((item) => {
                  return {value: item.id, key: item.name};
                }),
              );
            }}
            values={this.state.typeValue}
            name="type"
            placeholder="请选择一个类型"
            getValue={(value) => this.setState({typeValue: value.type})}
            initialValue={this.state.editorData?.typeInfo.id}
          ></SearchAbleSelect>
        </Form.Item>

        <Form.Item
          name="tag"
          label="文章标签"
          hasFeedback
          rules={[{required: false, message: '请选择文章标签'}]}
        >

          <SearchAbleSelect
            searchData={async (key) => {
              var datas: Array<any> = await APIS.ArticleAPI.SearchGetTagList(key);
              return Promise.resolve(
                datas.map((item) => {
                  return {value: item.id, key: item.tag};
                }),
              );
            }}
            maxCount={3}
            values={this.state.tagValue}
            name="tag"
            placeholder="请选择标签（最多3个）"
            isMultiple={true}
            getValue={(value) => this.setState({tagValue: value.tag})}
            initialValue={this.state.editorData?.tags.map((item: any) => {
              return item.id;
            })}
          ></SearchAbleSelect>
        </Form.Item>

        <Form.Item name="state" label="文章状态" valuePropName="checked">
          <Switch/>
        </Form.Item>
        <Form.Item
          name="image"
          label="封面预览图"
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <ImageUpload
            preImage={this.state.imageUrl}
            handleImageChange={(url: any) => (this.setState({imageUrl: url}))}
          ></ImageUpload>
        </Form.Item>
        <Form.Item>
          <RichTextEditor
            ref={(ref: any) => this.rich = ref}
            ContentInitialValue={this.state.editorData?.content}
            OnContentChanged={(content) => this.setState({articleContent: content})}
          ></RichTextEditor>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              {this.state.editorData ? '修改' : '新增'}
            </Button>
            <Button type="default" htmlType="button" onClick={() => this.props.history.goBack()}>
              取消
            </Button>
          </Space>
        </Form.Item>
      </Form>
    );
  }
}

export default connect()(CreateArticle);
